#!/bin/bash

# 端口切换脚本
# 功能：快速更改前后端端口配置
# 使用方法：./change-port.sh 8001

if [ $# -eq 0 ]; then
    echo "🔧 端口切换工具"
    echo "======================================"
    echo "用法: ./change-port.sh <新端口号>"
    echo "示例: ./change-port.sh 8001"
    echo "======================================"
    echo "当前配置:"
    echo "  后端端口: $(grep 'PORT:' backend/core/config.py | grep -o '[0-9]*')"
    echo "  前端API: $(grep 'NEXT_PUBLIC_API_BASE_URL' webui/.env.local 2>/dev/null || echo '未配置')"
    exit 1
fi

NEW_PORT=$1

# 验证端口号
if ! [[ "$NEW_PORT" =~ ^[0-9]+$ ]] || [ "$NEW_PORT" -lt 1024 ] || [ "$NEW_PORT" -gt 65535 ]; then
    echo "❌ 错误：端口号必须是1024-65535之间的数字"
    exit 1
fi

echo "🔧 正在切换到端口 $NEW_PORT..."

# 更新后端配置
sed -i.bak "s/PORT: int = [0-9]*/PORT: int = $NEW_PORT/" backend/core/config.py

# 更新前端环境变量
echo "NEXT_PUBLIC_API_BASE_URL=http://localhost:$NEW_PORT" > webui/.env.local

echo "✅ 端口切换完成！"
echo "======================================"
echo "新配置:"
echo "  后端端口: $NEW_PORT"
echo "  前端API: http://localhost:$NEW_PORT"
echo "======================================"
echo "💡 请重启服务以使配置生效："
echo "  ./stop.sh && ./start.sh" 